#    Copyright 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildCostEstimateForm(NumberOfEstimatesToDisplay=10):
    CompatibleUnitChoices=[]
    CompatibleUnits=CompatibleUnit.objects.all().order_by('Name')
    CompatibleUnitChoices.append(['-1', 'None'])
    for i in CompatibleUnits:
        CompatibleUnitChoices.append([i.id, str(i)])  
    Dict={}
    ContractChoices=[]
    Contracts=CompatibleUnitPriceContract.objects.all().filter(ActiveIndicator=True).order_by('Name')
    ContractChoices.append(['-1', 'None'])
    for i in Contracts:
        ContractChoices.append([i.id, str(i)])
    StakerWorkOrderChoices=[]
    StakerWorkOrders=StakerWorkOrder.objects.exclude(ArchivedIndicator=True).exclude(DeletedIndicator=True).order_by('Name')
    StakerWorkOrderChoices.append(['-1', 'None'])
    for i in StakerWorkOrders:
        StakerWorkOrderChoices.append([i.id, str(i)])
    Dict['QueryContract']=forms.ChoiceField(ContractChoices, required=False)
    Dict['QueryCompatibleUnit']=forms.ChoiceField(CompatibleUnitChoices, required=False)
    Dict['QueryStakerWorkOrder']=forms.ChoiceField(StakerWorkOrderChoices, required=False)
    Dict['QueryShowSummaryReport']=forms.BooleanField(required=False)
    Dict['Code']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'1'}))
    for i in range(0, NumberOfEstimatesToDisplay):
        Dict['CompatibleUnitPriceid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
        Dict['CompatibleUnit' + str(i)]=forms.ChoiceField(CompatibleUnitChoices, required=False)
        Dict['CodedInstallPrice' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
        Dict['CodedRemovePrice' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
        Dict['CompatibleUnitPriceContract' + str(i)]=forms.ChoiceField(ContractChoices, required=False)
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DeleteIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DecodedInstallPriceIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DecodedRemovePriceIndicator' + str(i)]=forms.BooleanField(required=False)
    return Dict

def ProcessCostEstimateForm(form, UserName):
    """Extracts the Query portion of the form"""
    try:
        compatibleUnitPriceContractid=COOPGIS_String.StringToDate(form.data['CompatibleUnitPriceContract'])
    except:
        compatibleUnitPriceContractid=0
    try:
        QueryCompatibleUnitid=int(form.data['QueryCompatibleUnit'])
        QueryCompatibleUnit=CompatibleUnit.objects.filter(id=QueryCompatibleUnitid)[0]
    except:
        QueryCompatibleUnit=None
    try:
        QueryStakerWorkOrderid=int(form.data['QueryStakerWorkOrder'])
        QueryStakerWorkOrder=StakerWorkOrder.objects.filter(id=QueryStakerWorkOrderid)[0]
    except:
        QueryStakerWorkOrder=None
    try:
        Code=form.data['Code']
    except:
        Code=None
    if(Code):
        try:
            Multiplier=float(Code.split('@')[0])
        except:
            Multiplier=None
        try:
            Adder=float(Code.split('@')[1])
        except:
            Adder=None
    else:
        Multiplier=None
        Adder=None
    try:
        QueryShowSummaryReport=bool(form.data['QueryShowSummaryReport'] == 'on')
    except:
        QueryShowSummaryReport=False
    return compatibleUnitPriceContractid, QueryCompatibleUnit, QueryStakerWorkOrder, Adder, Multiplier, QueryShowSummaryReport



def ProcessCostEstimateFormPrices(form, UserName, NumberOfCostEstimates, Adder, Multiplier):
    """Extracts and Processes Updates and Deletes for each CostEstimatePricePrice"""
    for CostEstimateNumber in range(0, NumberOfCostEstimates):
        try:
            UpdateIndicator=bool(form.data['UpdateIndicator' + str(CostEstimateNumber)] == 'on')
        except:
            UpdateIndicator=False
        try:
            DeleteIndicator=bool(form.data['DeleteIndicator' + str(CostEstimateNumber)] == 'on')
        except:
            DeleteIndicator=False
        try:
            CompatibleUnitPriceid=int(form.data['CompatibleUnitPriceid' + str(CostEstimateNumber)])
        except:
            CompatibleUnitPriceid='New'
        try:
            CompatibleUnitid=int(form.data['CompatibleUnit' + str(CostEstimateNumber)])
            compatibleUnit=CompatibleUnit.objects.filter(id=CompatibleUnitid)[0]
        except:
            compatibleUnit=None
        try:
            CodedInstallPrice=float(form.data['CodedInstallPrice' + str(CostEstimateNumber)])
        except:
            CodedInstallPrice='No Price'
        try:
            CodedRemovePrice=float(form.data['CodedRemovePrice' + str(CostEstimateNumber)])
        except:
            CodedRemovePrice='No Price'
        try:
            CompatibleUnitPriceContract=int(form.data['CompatibleUnitPriceContract' + str(CostEstimateNumber)])
            compatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract.objects.filter(id=CompatibleUnitPriceContract)[0]
            CompatibleUnitPriceContractid, CompatibleUnitPriceContractIndexWhenReverseSorted=compatibleUnitPriceContract.GetCommandidData()
        except:
            CompatibleUnitPriceContractid=None
            CompatibleUnitPriceContractIndexWhenReverseSorted=None

        try:
            DecodedInstallPriceIndicator=bool(form.data['DecodedInstallPriceIndicator' + str(CostEstimateNumber)] == 'on')
        except:
            DecodedInstallPriceIndicator=False
        try:
            DecodedRemovePriceIndicator=bool(form.data['DecodedRemovePriceIndicator' + str(CostEstimateNumber)] == 'on')
        except:
            DecodedRemovePriceIndicator=False
        try:
            Description=form.data['Description' + str(CostEstimateNumber)]
        except:
            Description=''
        if(DecodedInstallPriceIndicator and not(CodedInstallPrice == 'No Price') and Multiplier and Adder):
            CodedInstallPrice=(CodedInstallPrice + Adder) * Multiplier
        if(DecodedRemovePriceIndicator and not(CodedRemovePrice == 'No Price') and Multiplier and Adder):
            CodedRemovePrice=(CodedRemovePrice + Adder) * Multiplier

        if(UpdateIndicator and compatibleUnit and not(CodedInstallPrice == 'No Price') and not(CodedRemovePrice == 'No Price') and CompatibleUnitPriceContractid):
            if(CompatibleUnitPriceid=='New'):
                command=Command()
                command=command.Create(Name='CreateCompatibleUnitPrice', CommandUserName=UserName, CodedInstallPrice=CodedInstallPrice, 
                                       CodedRemovePrice=CodedRemovePrice, Description=Description,  
                                       CompatibleUnitPriceContractid=CompatibleUnitPriceContractid, 
                                       CompatibleUnitPriceContractIndexWhenReverseSorted=CompatibleUnitPriceContractIndexWhenReverseSorted,
                                       CompatibleUnitName=compatibleUnit.Name)
                command.Process()
            elif(int(CompatibleUnitPriceid) > 0):
                compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.filter(id=CompatibleUnitPriceid)[0]
                Objectid, ObjectIndexWhenReverseSorted=compatibleUnitPrice.GetCommandidData()
                command=Command()
                command=command.Create(Name='EditCompatibleUnitPrice', CommandUserName=UserName, CodedInstallPrice=CodedInstallPrice, 
                                       CodedRemovePrice=CodedRemovePrice, 
                                       CompatibleUnitPriceContractid=CompatibleUnitPriceContractid, 
                                       CompatibleUnitPriceContractIndexWhenReverseSorted=CompatibleUnitPriceContractIndexWhenReverseSorted,
                                       Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted)
                command.Process()
        elif(DeleteIndicator and not (CompatibleUnitPriceid == 'New')):
            compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.filter(id=CompatibleUnitPriceid)[0]
            if(compatibleUnitPrice.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='DeleteCompatibleUnitPrice', CommandUserName=UserName, CompatibleUnitPriceid=compatibleUnitPrice.id)
                command.Process()
            else:
                compatibleUnitPrice.CreateCommand.delete()
                compatibleUnitPrice.delete()


def PopulateCostEstimateForm(form, UserName, QueryContract,QueryCompatibleUnit, NumberOfCostEstimates):
    CompatibleUnitPrices=compatibleunit.CompatibleUnitPrice.objects.all()
    if(QueryContract):
        CompatibleUnitPrices=CompatibleUnitPrices.filter(CompatibleUnitPriceContract__id=QueryContract)
    if(QueryCompatibleUnit):
        CompatibleUnitPrices=CompatibleUnitPrices.filter(CompatibleUnit=QueryCompatibleUnit)
    CompatibleUnitPrices=CompatibleUnitPrices.order_by('id')
    for CostEstimateNumber in range(0, NumberOfCostEstimates):
        try:
            form.data['UpdateIndicator' + str(CostEstimateNumber)] = False
            form.data['DeleteIndicator' + str(CostEstimateNumber)] = False
            form.data['CompatibleUnitPriceid' + str(CostEstimateNumber)] = CompatibleUnitPrices[CostEstimateNumber].id
            form.data['CompatibleUnit' + str(CostEstimateNumber)] = CompatibleUnitPrices[CostEstimateNumber].CompatibleUnit.id
            form.data['CodedInstallPrice' + str(CostEstimateNumber)] = CompatibleUnitPrices[CostEstimateNumber].CodedInstallPrice
            form.data['CodedRemovePrice' + str(CostEstimateNumber)] = CompatibleUnitPrices[CostEstimateNumber].CodedRemovePrice
            form.data['CompatibleUnitPriceContract' + str(CostEstimateNumber)] = CompatibleUnitPrices[CostEstimateNumber].CompatibleUnitPriceContract.id
            form.data['DecodedInstallPriceIndicator' + str(CostEstimateNumber)]=False
            form.data['DecodedRemovePriceIndicator' + str(CostEstimateNumber)]=False
        except:
            form.data['UpdateIndicator' + str(CostEstimateNumber)] = False
            form.data['DeleteIndicator' + str(CostEstimateNumber)] = False
            form.data['CompatibleUnitPriceid' + str(CostEstimateNumber)] = ''
            form.data['CompatibleUnit' + str(CostEstimateNumber)] = -1
            form.data['CodedInstallPrice' + str(CostEstimateNumber)] = ''
            form.data['CodedRemovePrice' + str(CostEstimateNumber)] = ''
            form.data['CompatibleUnitPriceContract' + str(CostEstimateNumber)] = -1
            form.data['DecodedInstallPriceIndicator' + str(CostEstimateNumber)]=False
            form.data['DecodedRemovePriceIndicator' + str(CostEstimateNumber)]=False

    


def BuildCostEstimateContractForm(NumberOfContractsToDisplay=10):
    CompatibleUnitPriceContractChoices=[]
    CompatibleUnitPriceContracts=compatibleunit.CompatibleUnitPriceContract.objects.all().order_by('Name')
    CompatibleUnitPriceContractChoices.append(['-1', 'None'])
    for i in CompatibleUnitPriceContracts:
        CompatibleUnitPriceContractChoices.append([i.id, str(i)])  
    Dict={}
    CompanyChoices=[]
    Companies=Company.objects.all().filter(ContractorIndicator=True).order_by('Name')
    CompanyChoices.append(['-1', 'None'])
    for i in Companies:
        CompanyChoices.append([i.id, str(i)])

    for i in range(0, NumberOfContractsToDisplay):
        Dict['CompatibleUnitPriceContractid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
        Dict['Description' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
        Dict['Company' + str(i)]=forms.ChoiceField(CompanyChoices, required=False)
        Dict['StartDate' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
        Dict['EndDate' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
        Dict['Name' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
        Dict['ActiveIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DeleteIndicator' + str(i)]=forms.BooleanField(required=False)
    return Dict



def ProcessCostEstimateContractForm(form, UserName, NumberOfContracts):
    """Creates, Edits, and Deletes CompatibleUnitPriceContract instances"""
    for ContractNumber in range(0, NumberOfContracts):
        try:
            UpdateIndicator=bool(form.data['UpdateIndicator' + str(ContractNumber)] == 'on')
        except:
            UpdateIndicator=False
        try:
            DeleteIndicator=bool(form.data['DeleteIndicator' + str(ContractNumber)] == 'on')
        except:
            DeleteIndicator=False
        try:
            CompatibleUnitPriceContractid=int(form.data['CompatibleUnitPriceContractid' + str(ContractNumber)])
        except:
            CompatibleUnitPriceContractid='New'
        try:
            Companyid=int(form.data['Company' + str(ContractNumber)])
            company=Company.objects.filter(id=Companyid)[0]
            CompanyName=company.Name
        except:
            company=None
            CompanyName=''
        try:
            StartDate=COOPGIS_String.StringToDate(form.data['StartDate' + str(ContractNumber)])
        except:
            StartDate=None
        try:
            EndDate=COOPGIS_String.StringToDate(form.data['EndDate' + str(ContractNumber)])
        except:
            EndDate=None
        try:
            Description=form.data['Description' + str(ContractNumber)]
        except:
            Description=''
        try:
            Name=form.data['Name' + str(ContractNumber)]
        except:
            Name=''
        try:
            ActiveIndicator=bool(form.data['ActiveIndicator' + str(ContractNumber)] == 'on')
        except:
            ActiveIndicator=False
 
        if(UpdateIndicator and company and StartDate and EndDate):
            if(CompatibleUnitPriceContractid=='New'):
                command=Command()
                command=command.Create(Name='CreateCompatibleUnitPriceContract', CommandUserName=UserName, 
                                       ObjectName=Name, Description=Description, ActiveIndicator=ActiveIndicator,
                                       StartDate=StartDate, EndDate=EndDate, CompanyName=CompanyName)
                command.Process()
            elif(int(CompatibleUnitPriceContractid) > 0):
                compatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract.objects.filter(id=CompatibleUnitPriceContractid)[0]
                Objectid, ObjectIndexWhenReverseSorted=compatibleUnitPriceContract.GetCommandidData()
                command=Command()
                #raise(Exception('Made it here'))

                command=command.Create(Name='EditCompatibleUnitPriceContract', CommandUserName=UserName, 
                                       ObjectName=Name, Description=Description, ActiveIndicator=ActiveIndicator,
                                       StartDate=StartDate, EndDate=EndDate, CompanyName=CompanyName,
                                       Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted)
                command.Process()
        elif(DeleteIndicator and not (CompatibleUnitPriceContractid == 'New')):
            compatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract.objects.filter(id=CompatibleUnitPriceContractid)[0]
            if(compatibleUnitPriceContract.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='DeleteCompatibleUnitPriceContract', CommandUserName=UserName, CompatibleUnitPriceid=compatibleUnitPriceContract.id)
                command.Process()
            else:
                if(compatibleUnitPriceContract.CreateCommand):
                    compatibleUnitPriceContract.CreateCommand.delete()
                compatibleUnitPriceContract.delete()




def PopulateCostEstimateContractForm(form, UserName, NumberOfContracts):
    CompatibleUnitPriceContracts=compatibleunit.CompatibleUnitPriceContract.objects.all().order_by('Name')
    for ContractNumber in range(0, NumberOfContracts):
        try:    
            form.setData({'UpdateIndicator' + str(ContractNumber) : False})
            form.setData({'DeleteIndicator' + str(ContractNumber) : False})
            form.setData({'CompatibleUnitPriceContractid' + str(ContractNumber) : str(CompatibleUnitPriceContracts[ContractNumber].id)})
            form.setData({'Company' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].Company.id})
            form.setData({'Description' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].Description})
            form.setData({'Name' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].Name})
            form.setData({'StartDate' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].StartDate})
            form.setData({'EndDate' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].EndDate})
            form.setData({'ActiveIndicator' + str(ContractNumber) : CompatibleUnitPriceContracts[ContractNumber].ActiveIndicator})
            #raise(Exception(str(str(CompatibleUnitPriceContracts[ContractNumber].id)) + str(ContractNumber) ))
        except IndexError:
            form.setData({'UpdateIndicator' + str(ContractNumber) : False})
            form.setData({'DeleteIndicator' + str(ContractNumber) : False})
            form.setData({'CompatibleUnitPriceContractid' + str(ContractNumber) : ''})
            form.setData({'Company' + str(ContractNumber) : -1})
            form.setData({'Description' + str(ContractNumber) : ''})
            form.setData({'Name' + str(ContractNumber) : ''})
            form.setData({'StartDate' + str(ContractNumber) : ''})
            form.setData({'EndDate' + str(ContractNumber) : ''})
            form.setData({'ActiveIndicator' + str(ContractNumber) : False})

